/*
 * Copyright (C) 2012-2013 Michael L.R. Marques
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 * 
 * Contact: michaellrmarques@gmail.com
 * JMKeyboard.java
 * Created on Nov 7, 2011, 11:03:50 AM
 */

package com.jm.commons.components.keyboard;

import com.jm.commons.ui.UIBounds;
import java.awt.Color;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;

/**
 * 
 * @author Michael L.R. Marques
 */
public class JMKeyboard extends javax.swing.JDialog {
    
    public static final int ALPHABETICAL_INPUT = 0;
    public static final int NUMERICAL_INPUT = 1;
    public static final int EMAIL_INPUT = 2;
    public static final int CURRENCY_INPUT = 3;
    
    public static final int SINGLE_UPPER_CASE = 0;
    public static final int UPPER_CASE = 1;
    public static final int LOWER_CASE = 2;
    
    private static final String[] QWERTY = {"Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "A", "S", "D", "F", "G", "H", "J", "K", "L", ",", "\\", "Z", "X", "C", "V", "B", "N", "M", "."};
    private static final String QWERTY_TEXT = "ABC";
    private static final String[] SYMNUM = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "(", ")", "{", "}", "[", "]", "\\", "/", ":", ";", "\"", "'", "@", "!", "&", "#", "?", ",", "."};
    private static final String SYMNUM_TEXT = "123?@.";
    
    private ActionListener returnAction;
    
    private JTextComponent textComponent;
    
    private int inputType;
    private int letterCase;
    
    /**
     * Creates new form JMKeyboard
     * @param parent
     * @param modal
     * @param textComponent
     * @param inputType 
     */
    private JMKeyboard(Frame parent, boolean modal, JTextComponent textComponent, int inputType) {
        super(parent, modal);
        initComponents();
        setBounds(UIBounds.getBounds(parent, getBounds()));
        
        this.textComponent = textComponent;
        this.inputType = inputType;
        this.letterCase = SINGLE_UPPER_CASE;
        
        this.tfText.setText(this.textComponent.getText());
        
        pnlKeys.setLayout(new GridLayout());
        ((GridLayout) pnlKeys.getLayout()).setRows(3);
        
        initActionListeners();
        initKeyboard();
        
        JColorChooser.showDialog(textComponent, QWERTY_TEXT, Color.yellow);
    }
    
    /**
     * 
     * @return 
     */
    public String getText() {
        return this.tfText.getText();
    }
    
    /**
     * 
     * @param text 
     */
    public void setText(String text) {
        this.tfText.setText(text);
    }
    
    /**
     * 
     * @return 
     */
    public int getInputType() {
        return this.inputType;
    }
    
    /**
     * 
     * @return 
     */
    public int getLetterCase() {
        return this.letterCase;
    }
    
    /**
     * 
     * @param inputType 
     */
    public void setInputType(int inputType) {
        this.inputType = inputType;
        initKeyboard();
    }
    
    /**
     * 
     * @param letterCase 
     */
    public void setLetterCase(int letterCase) {
        this.letterCase = letterCase;
    }
    
    /**
     * 
     * @param text 
     */
    private void insertText(String text) {
        switch(letterCase) {
            case SINGLE_UPPER_CASE:
                text = text.toUpperCase();
                letterCase = LOWER_CASE;
                break;
            case UPPER_CASE:
                text = text.toUpperCase();
                break;
            case LOWER_CASE:
                text = text.toLowerCase();
                break;
        }
        
        if(tfText.getCaretPosition() == tfText.getText().length()) {
            tfText.setText(tfText.getText() + text);
        } else if (tfText.getSelectedText() != null) {
            tfText.replaceSelection(text);
        } else {
            tfText.setText(tfText.getText().substring(0, tfText.getCaretPosition()) + text + tfText.getText().substring(tfText.getCaretPosition(), tfText.getText().length()));
        }
    }
    
    /**
     * 
     */
    private void initKeyboard() {
        pnlKeys.removeAll();
        String[] inputKeys = new String[0];
        String inputTypeKey = "";
        
        switch(inputType) {
            case ALPHABETICAL_INPUT:
                inputKeys = QWERTY;
                inputTypeKey = SYMNUM_TEXT;
                break;
            case NUMERICAL_INPUT:
                inputKeys = SYMNUM;
                inputTypeKey = QWERTY_TEXT;
                break;
            case EMAIL_INPUT:
                inputKeys = QWERTY;
                inputTypeKey = SYMNUM_TEXT;
                break;
            case CURRENCY_INPUT:
                inputKeys = SYMNUM;
                inputTypeKey = QWERTY_TEXT;
                break;
        }
                
        for(String s : inputKeys) {
            pnlKeys.add(new JMButton(s));
        }
        JButton button = new JButton("Return");
        button.addActionListener(returnAction);
        pnlKeys.add(button);
        btnChangeInput1.setText(inputTypeKey);
        btnChangeInput2.setText(inputTypeKey);
    }
    
    /**
     * 
     */
    private void initActionListeners() {
        ActionListener inputTypeChangeAction = new ActionListener() {
            @Override public void actionPerformed(ActionEvent e) {
                if(inputType > ALPHABETICAL_INPUT) {
                    inputType = ALPHABETICAL_INPUT;
                } else {
                    inputType = NUMERICAL_INPUT;
                }

                initKeyboard();
            }
        };
        btnChangeInput1.addActionListener(inputTypeChangeAction);
        btnChangeInput2.addActionListener(inputTypeChangeAction);
        
        MouseAdapter shiftAction = new MouseAdapter() {
            @Override public void mouseClicked(MouseEvent e) {
                if(e.getClickCount() == 1) {
                    if(letterCase == SINGLE_UPPER_CASE) {
                        letterCase = LOWER_CASE;
                    } else {
                        letterCase = SINGLE_UPPER_CASE;
                    }
                } else if(e.getClickCount() == 2) {
                    if(letterCase == UPPER_CASE) {
                        letterCase = LOWER_CASE;
                    } else {
                        letterCase = UPPER_CASE;
                    }
                }
            }
        };
        btnShift1.addMouseListener(shiftAction);
        btnShift2.addMouseListener(shiftAction);
        
        returnAction = new ActionListener() {
            @Override public void actionPerformed(ActionEvent e) {
                textComponent.setText(getText());
                setVisible(false);
                dispose();
            }
        };
        
        btnSpace.addActionListener(new ActionListener() {
            @Override public void actionPerformed(ActionEvent e) {
                insertText(" ");
            }
        });
    }
    
    /**
     * 
     * @param parent
     * @param component 
     */
    public static void show(Frame parent, JTextComponent component) {
        show(parent, component, ALPHABETICAL_INPUT);
    }
    
    /**
     * 
     * @param parent
     * @param component
     * @param inputType 
     */
    public static void show(Frame parent, JTextComponent component, int inputType) {
        JMKeyboard keyboard = new JMKeyboard(parent, true, component, inputType);
        keyboard.setVisible(true);
    }

    /**
     * initialize the form.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlMain = new javax.swing.JPanel();
        tfText = new javax.swing.JTextField();
        pnlKeys = new javax.swing.JPanel();
        btnSpace = new javax.swing.JButton();
        btnShift2 = new javax.swing.JButton();
        btnChangeInput2 = new javax.swing.JButton();
        btnShift1 = new javax.swing.JButton();
        btnChangeInput1 = new javax.swing.JButton();
        btnBackSpace = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setUndecorated(true);
        setResizable(false);

        pnlMain.setOpaque(false);

        tfText.setFont(new java.awt.Font("Arial", 0, 20)); // NOI18N
        tfText.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        pnlKeys.setOpaque(false);

        javax.swing.GroupLayout pnlKeysLayout = new javax.swing.GroupLayout(pnlKeys);
        pnlKeys.setLayout(pnlKeysLayout);
        pnlKeysLayout.setHorizontalGroup(
            pnlKeysLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        pnlKeysLayout.setVerticalGroup(
            pnlKeysLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 199, Short.MAX_VALUE)
        );

        btnSpace.setFocusable(false);

        btnShift2.setText("Shift");
        btnShift2.setFocusable(false);

        btnChangeInput2.setFocusable(false);

        btnShift1.setText("Shift");
        btnShift1.setFocusable(false);

        btnChangeInput1.setFocusable(false);

        btnBackSpace.setText("Backspace");
        btnBackSpace.setFocusable(false);
        btnBackSpace.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBackSpaceActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlMainLayout = new javax.swing.GroupLayout(pnlMain);
        pnlMain.setLayout(pnlMainLayout);
        pnlMainLayout.setHorizontalGroup(
            pnlMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlMainLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(pnlKeys, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, pnlMainLayout.createSequentialGroup()
                        .addComponent(btnShift1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnChangeInput1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSpace, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnChangeInput2, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnShift2, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, pnlMainLayout.createSequentialGroup()
                        .addComponent(tfText, javax.swing.GroupLayout.PREFERRED_SIZE, 747, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnBackSpace, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );

        pnlMainLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnChangeInput1, btnChangeInput2, btnShift1, btnShift2});

        pnlMainLayout.setVerticalGroup(
            pnlMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlMainLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnBackSpace, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(tfText, javax.swing.GroupLayout.DEFAULT_SIZE, 39, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlKeys, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE, false)
                    .addComponent(btnSpace, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnShift2)
                    .addComponent(btnChangeInput2)
                    .addComponent(btnShift1)
                    .addComponent(btnChangeInput1))
                .addContainerGap())
        );

        pnlMainLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnChangeInput1, btnChangeInput2, btnShift1, btnShift2, btnSpace});

        pnlMainLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnBackSpace, tfText});

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlMain, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlMain, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnBackSpaceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBackSpaceActionPerformed
        if(!tfText.getText().isEmpty()) {
            if(tfText.getCaretPosition() == tfText.getText().length()) {
                try {
                    tfText.setText(tfText.getText(0, tfText.getText().length()-1));
                } catch (BadLocationException ble) {
                    ble.printStackTrace();
                }
            } else if (tfText.getSelectedText() != null) {
                tfText.replaceSelection("");
            } else {
                int caretPos = tfText.getCaretPosition();
                if(caretPos > 0) {
                    tfText.setText(tfText.getText().substring(0, caretPos-1) + tfText.getText().substring(caretPos, tfText.getText().length()));
                    tfText.setCaretPosition(caretPos-1);
                }
            }
        }
    }//GEN-LAST:event_btnBackSpaceActionPerformed
    
    /**
     * 
     */
    class JMButton extends JButton {
        
        /**
         * 
         * @param text 
         */
        public JMButton(String text) {
            super(text);
            setFocusable(false);
            this.addActionListener(new ActionListener() {
                @Override public void actionPerformed(ActionEvent e) {
                    insertText(getText());
                }
            });
        }

    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBackSpace;
    private javax.swing.JButton btnChangeInput1;
    private javax.swing.JButton btnChangeInput2;
    private javax.swing.JButton btnShift1;
    private javax.swing.JButton btnShift2;
    private javax.swing.JButton btnSpace;
    private javax.swing.JPanel pnlKeys;
    private javax.swing.JPanel pnlMain;
    private javax.swing.JTextField tfText;
    // End of variables declaration//GEN-END:variables

}
